<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactMessageBatchSend\Action\Workbench;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\WorkbenchAuthMiddleware;
use MoChat\App\WorkContact\Action\Dashboard\Traits\FilterContactTraits;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ContactMessageBatchSend\Contract\ContactMessageBatchSendResultContract;
use MoChat\Plugin\ContactMessageBatchSend\Logic\ShowLogic;

/**
 * 客户群发 - 详情.
 * @Controller
 */
class Show extends AbstractAction
{
    use ValidateSceneTrait;
    use FilterContactTraits;

    /**
     * @Inject
     * @var ContactMessageBatchSendResultContract
     */
    protected $contactMessageBatchSendResultService;

    /**
     * @Inject
     * @var WorkContactContract
     */
    protected $workContactService;

    /**
     * @Inject
     * @var ShowLogic
     */
    private $showLogic;

    /**
     * @Middlewares({
     *     @Middleware(WorkbenchAuthMiddleware::class)
     * })
     * @RequestMapping(path="/workbench/contactMessageBatchSend/show", methods="GET")
     */
    public function handle(): array
    {
        // 接收参数
        $user = user();
        $corpId = (int) $user['corpId'];
        $employeeId = (int) $user['id'];

        // 参数验证
        $this->validated($this->request->all());
        $batchId = (int) $this->request->input('batchId');
        // 接收参数
        $params = [
            'batchId' => $batchId,
        ];
        // 群发消息详情
        $info = $this->showLogic->handle($params, $employeeId);
        // 群发客户处理（群发结果中客户为群发客户，若为空根据筛选条件获取客户）
        $sendResult = $this->contactMessageBatchSendResultService->getContactMessageBatchSendResultByBatchId($batchId, ['contact_id']);
        $info['sendContact'] = [];
        if (! empty($sendResult)) {
            $contactIds = array_unique(array_column($sendResult, 'contactId'));
            $contacts = $this->workContactService->getWorkContactsById($contactIds, ['name']);
            empty($contacts) || $info['sendContact'] = array_column($contacts, 'name');
        } else {
            $filterParams = $info['filterParams'];
            $data = [
                'corpId' => $corpId,
                'employeeIds' => $info['employeeIds'] ?? [], // 员工ids
                'gender' => $filterParams['gender'] ?? '', // 性别：0-未知 1-男性 2-女性
                'tagIds' => $filterParams['tags'] ?? [], // 客户标签
                'startTime' => $filterParams['addTimeStart'] ?? '', // 添加时间-开始
                'endTime' => $filterParams['addTimeEnd'] ?? '', // 添加时间-结束
                'roomIds' => $filterParams['rooms'] ?? [], // 客户所在群聊
                'deleteTagIds' => $filterParams['removeTags'] ?? [], // 排除客户标签
            ];
            $filterContact = $this->filterContact($data);
            if (! empty($filterContact['list'])) {
                $contactIds = array_unique(array_column($filterContact['list'], 'id'));
                $contacts = $this->workContactService->getWorkContactsById($contactIds, ['name']);
                empty($contacts) || $info['sendContact'] = array_column($contacts, 'name');
            }
        }
        return $info;
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [];
    }
}
